<?php

namespace App\Repositories;

use Exception;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Exceptions\GeneralException;

/**
 * 用户模块Repository
 *
 * Date: 2018/05/18
 * @author Tenny
 * @package App\Repositories
 */
class UserRepository extends BaseRepository
{
    /**
     * 定义模型类
     *
     * Date: 2018/05/18
     * @author Tenny
     * @return mixed|string
     */
    public function model()
    {
        return User::class;
    }

    /**
     * 根据服务站获取用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $server_id
     * @param $name
     * @param $created_at
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getUsers($server_id, $name, $created_at, $limit = 15)
    {
        $query = \DB::table('user as u');
        if ($server_id !== false) {
            $query->where('u.server_id', '=', $server_id);
        }
        if ($name !== false) {
            $query->where('u.name', 'like', '%' . $name . '%');
        }
        if ($created_at != false) {
            $query->whereBetween('u.created_at', $created_at);
        }
        $users = $query
            ->select(['u.id', 'u.name', 'u.phone', 'u.gender', 'u.avatar', 'u.reg_type', 'u.service_id', 'u.status', 'u.send_type', 'u.appointment_time', 'u.home_address', 'u.company_address', 'u.nickname', 'u.created_at', 's.designation as service_name'])
            ->leftJoin('service as s', 'u.service_id', '=', 's.id')
            ->whereNull('u.deleted_at')
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $users;
    }

    /**
     * 根据uid获取用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $uid
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder
     * @throws \App\Exceptions\GeneralException
     */
    public function getUsersDetails($uid, $limit)
    {
        $query = DB::table('user as u');
        $uid_info = $query
            ->select(['u.id', 'u.name', 'u.phone', 'u.gender', 'u.avatar', 'u.reg_type', 'u.service_id', 'u.status', 'u.send_type', 'u.appointment_time', 'u.home_address', 'u.company_address', 'u.nickname', 'u.created_at', 's.designation as service_name'])
            ->leftJoin('service as s', 'u.service_id', '=', 's.id')
            ->where('u.id', '=', $uid)
            ->first();
        //计算派送件
        $zt_num = DB::table('order')
            ->select(DB::raw('count(*) as zt_num'))
            ->where('type', '!=', '1')
            ->where('to_mobile', '=', $uid_info->phone)
            ->first();
        $uid_info->zt_num = $zt_num->zt_num;
        //计算自提件
        $ps_num = DB::table('order')
            ->select(DB::raw('count(order_id) as ps_num'))
            ->where('type', '=', '1')
            ->where('to_mobile', '=', $uid_info->phone)
            ->first();
        $uid_info->ps_num = $ps_num->ps_num;
        //查询用户地址
        $user_address = DB::table('user_address')
            ->select(['name', 'phone', 'province_id', 'province', 'city_id', 'city', 'county_id', 'county', 'address', 'type', 'tag'])
            ->where('uid', '=', $uid_info->id)
            ->get();
        $uid_info->user_address = $user_address;
        //查询用户操作日志
        $userLogRepository = new UserLogRepository;
        $user_log = $userLogRepository->getLog($uid_info->id, false, 1, false, $limit);
        $uid_info->user_log = $user_log;
        unset($zt_num, $ps_num, $user_address, $user_log);
        return $uid_info;
    }

    /**
     * 根据uid获取用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $uid
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getUsersInfo($uid)
    {
        $query = DB::table('user as u');
        $uid_info = $query
            ->select(['u.id', 'u.name', 'u.phone', 'u.gender', 'u.avatar', 'u.reg_type', 'u.service_id', 'u.status', 'u.send_type', 'u.appointment_time', 'u.home_address', 'u.company_address', 'u.nickname', 'u.created_at', 's.designation as service_name'])
            ->leftJoin('service as s', 'u.service_id', '=', 's.id')
            ->where('u.id', '=', $uid)
            ->first();
        return $uid_info;
    }

    /**
     * 获取用户权限
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param User $user
     * @return \Illuminate\Support\Collection
     */
    public function getPermissions(User $user)
    {
        return $user->position()->with('permissions')->pluck('code');
    }

    /**
     * 修改用户密码
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $oldPassword
     * @param $newPassword
     * @param User $user
     * @return bool
     * @throws \Throwable
     */
    public function modifyPassword($oldPassword, $newPassword, User $user): bool
    {
        $result = $this->verifyPassword($user, $oldPassword);

        if ($result) {
            $user->password = $newPassword;
            return $user->saveOrFail();
        }

        return false;
    }

    /**
     * 验证给定项目和日期范围是否存在记录
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param int $project
     * @param Carbon $start
     * @param Carbon $end
     * @return bool
     */
    public function memberOfProjectByDateRange(int $project, Carbon $start, Carbon $end)
    {
        $count = $this->projects()->where('projects.id', $project)->where('type', '<>', 'main')
            ->whereBetween('start', [$start, $end])
            ->orWhereBetween('end', [$start, $end])
            ->orWhere('start', '<', $start)
            ->where('end', '>', $end)->count();
        return $count > 0;
    }

    /**
     * 获取用户的主项目信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $user
     * @return Project|null
     */
    public function mainProject($user)
    {
        $project = null;

        if (is_integer($user)) {
            $project = $this->projects()->where('users.id', $user)->where('type', '=', 'main')->first();
        } elseif ($user instanceof User) {
            $project = $user->projects()->where('type', '=', 'main')->first();
        }
        return $project;
    }

    /**
     * 修改头像
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param string $path
     * @param User $user
     * @return bool
     * @throws \Throwable
     */
    public function modifyAvatar(string $path, User $user): bool
    {
        $user->avatar = $path;
        return $user->saveOrFail();
    }

    /**
     * 验证用户密码
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param User $user
     * @param $plain
     * @return bool
     */
    public function verifyPassword(User $user, $plain)
    {
        return Hash::check($plain, $user->getAuthPassword());
    }

    /**
     * 更新用户身份信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param array $attributes
     * @return \Illuminate\Database\Eloquent\Model
     * @throws GeneralException
     */
    public function modifyIdentification(array $attributes)
    {
        try {
            return Identification::updateOrCreate($attributes, array_values($attributes));
        } catch (Exception $exception) {
            throw new GeneralException('更新用户身份信息失败');
        }
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}
